let city = ''
$.ajax({
  url: "../city.json",
  data: { action: "jQueryAjax" },
  type: "GET",
  async: false,
  success: function (data) {
    city = data
  },
  //返回数据的格式
  dataType: "json"
})
const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      rules: {
        // Dealer_Name: [{ required: true, message: '请输入经销商名称', trigger: 'blur' }],
        // Tax_Number: [{ required: true, message: '请输入纳税识别号', trigger: 'blur' }],
        // Account_Number: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
        // Dealer_Address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        // address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
      },
      brand: [],
      article: [],
      text: [],
      // 整个省市县数据
      city,
      // 被选中的市数据
      cityList: [],
      // 被选中的县数据
      areaList: [],
      isdisabled: true,
      selectProvince: {},
      selectCity: {},
      selectArea: {},
      address: '',
      dialogImageUrl: '',
      dialogVisible: false,
      dealer_bank_pic: [],
      fileList: [],
      form: {
        Dealer_SerialNumber: "",//经销商流水号
        Dealer_Name: '',//经销商名字
        Tax_Number: '',//纳税识别号
        Dealer_Address: '',//经销商地址
        Account_Number: '', //预收款银行卡号
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Children: {
          dealer_bank_account: [{
            Dealer_Bank_Account_SerialNumber: "",//经销商银行流水号
            Bank_Name: '',//开户银行
            Account_Number: '',//账号
          }],
          dealer_bank_pic: [{ //经销商材料上传
            Dealer_Bank_Pic_SerialNumber: "",//材料流水号
            Picture_Url: '',//图片地址
          }],
        }
      },
      loading: false,
      value: [],
    }
  },
  mounted() {
    this.form.Enterprise_Info_SerialNumber = $.cookie("enterprise");
    let Primary_Key = sessionStorage.getItem("Dealer_SerialNumber");
    this.get_original_value(Primary_Key);
  },
  methods: {
    //查原值
    get_original_value(Primary_Key) {
      let _this = this
      $.ajax({
        url: DomainName + '/getSubtableInquiryOriginal?token=' + $.cookie("token"),
        data: {
          JSONObject: JSON.stringify({
            dealer_info: {
              dealer_bank_account: {}, dealer_bank_pic: {}
            }
          }),
          Primary_Key
        },
        success: function (res) {
          console.log(res);
          _this.form = res.dealer_info[0]
          _this.value = res.dealer_info[0].Dealer_Address.split('/').slice(0, 3)
          _this.address = res.dealer_info[0].Dealer_Address.split('/')[3]
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    //记得更改主表名
    submitForm() {
      this.form.Dealer_Address = `${this.value[0]}/${this.value[1]}/${this.value[2]}/${this.address}`
      const _this = this;
      _this.loading = true;
      const { add, modify } = _this.deal()
      let data = {}
      if (add == null) {
        data = { Data: JSON.stringify({ Modify: { dealer_info: [modify] } }) }
      } else {
        data = {
          Data: JSON.stringify(
            {
              Modify: { dealer_info: [modify] },
              Add: { dealer_info: [add] }
            }
          ),
        }
      }
      $.ajax({
        url: DomainName + '/getEditAction?token=' + $.cookie("token"),
        type: 'POST',
        data,
        success: function (res) {
          console.log('提交结果', res)
          _this.$message.success("提交成功")
          window.history.go(-1);
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)

      let add_dealer_bank_account = [], modify_dealer_bank_account = []
      let add_dealer_bank_pic = [], modify_dealer_bank_pic = []

      for (const i in modify.Children.dealer_bank_account) {
        const obj = modify.Children.dealer_bank_account[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_dealer_bank_account.push(obj)
        } else {
          modify_dealer_bank_account.push(obj)
        }
      }
      for (const i in modify.Children.dealer_bank_pic) {
        const obj = modify.Children.dealer_bank_pic[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_dealer_bank_pic.push(obj)
        } else {
          modify_dealer_bank_pic.push(obj)
        }
      }
      add.Children.dealer_bank_account = add_dealer_bank_account
      modify.Children.dealer_bank_account = modify_dealer_bank_account

      add.Children.dealer_bank_pic = add_dealer_bank_pic
      modify.Children.dealer_bank_pic = modify_dealer_bank_pic
      if (add_dealer_bank_pic.length == 0 || add_dealer_bank_account.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    //供应商相关材料照片
    upload(file) {
      let _this = this
      new Compressor(file, {
        quality: 0.08,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            _this.form.Children.dealer_bank_pic[0].pic = e.target.result
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                if (Result.Status == "success") {
                  _this.form.Children.dealer_bank_pic[0].Picture_Url = Result.Picture_Url
                } else {
                  _this.$message.error(Result.msg)
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //查看图片
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file
    },
    //删除图片
    handleRemove() {
      this.form.Children.dealer_bank_pic[0].Picture_Url = ""
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 省份 市 县联动
    // selectProvinceFun(event) {
    //   console.log(event)
    //   if (event) {
    //     this.cityList = event.children
    //   } else {
    //     this.cityList = []
    //   }
    //   this.areaList = []
    // },
    // selectCityFun(event) {
    //   console.log(event)
    //   if (event) {
    //     this.areaList = event.children
    //   } else {
    //     this.areaList = []
    //   }
    // },
    // selectAreaFun(event) {
    //   if (event) {
    //     console.log(event)
    //     this.isdisabled = false
    //   } else {
    //     this.isdisabled = true
    //   }
    // },
    // selectAddress(event) {
    //   if (event && event != '' && this.selectArea.label != undefined) {
    //     this.form.Dealer_Address = this.selectProvince.label
    //       + this.selectCity.label
    //       + this.selectArea.label
    //       + this.address
    //   }
    // }
  }
})